package com.health.medical.controller;

import java.util.List;

import jakarta.servlet.http.HttpServletResponse;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.health.common.annotation.Log;
import com.health.common.core.controller.BaseController;
import com.health.common.core.domain.AjaxResult;
import com.health.common.enums.BusinessType;
import com.health.medical.domain.MedicalDoctor;
import com.health.medical.domain.dto.DoctorDetailDTO;
import com.health.medical.service.IMedicalDoctorService;
import com.health.common.utils.poi.ExcelUtil;
import com.health.common.core.page.TableDataInfo;
import org.springframework.web.multipart.MultipartFile;

/**
 * 医生管理Controller
 */
@RestController
@RequestMapping("/medical/doctor")
public class MedicalDoctorController extends BaseController
{
    @Autowired
    private IMedicalDoctorService medicalDoctorService;
    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 查询医生管理列表 - 使用多表联查返回带机构名和科室名的数据
     */
    //@PreAuthorize("@ss.hasPermi('medical:doctor:list')")
    @GetMapping("/list")
    public TableDataInfo list(MedicalDoctor medicalDoctor)
    {
        startPage();
        List<DoctorDetailDTO> list = medicalDoctorService.selectDoctorDetailList(medicalDoctor);
        return getDataTable(list);
    }

    /**
     * 导出医生管理列表 - 保持原样，使用单表查询
     */
    @PreAuthorize("@ss.hasPermi('medical:doctor:export')")
    @Log(title = "医生管理", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, MedicalDoctor medicalDoctor)
    {
        List<MedicalDoctor> list = medicalDoctorService.selectMedicalDoctorList(medicalDoctor);
        ExcelUtil<MedicalDoctor> util = new ExcelUtil<MedicalDoctor>(MedicalDoctor.class);
        util.exportExcel(response, list, "医生管理数据");
    }

    /**
     * 获取医生管理详细信息 - 使用多表联查返回带机构名和科室名的详情
     */
    @PreAuthorize("@ss.hasPermi('medical:doctor:query')")
    @GetMapping(value = "/{doctorId}")
    public AjaxResult getInfo(@PathVariable("doctorId") Long doctorId)
    {
        DoctorDetailDTO doctorDetail = medicalDoctorService.selectDoctorDetailByDoctorId(doctorId);
        return success(doctorDetail);
    }

    /**
     * 新增医生管理
     */
    @PreAuthorize("@ss.hasPermi('medical:doctor:add')")
    @Log(title = "医生管理", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody MedicalDoctor medicalDoctor)
    {
        return toAjax(medicalDoctorService.insertMedicalDoctor(medicalDoctor));
    }

    /**
     * 修改医生管理
     */
    @PreAuthorize("@ss.hasPermi('medical:doctor:edit')")
    @Log(title = "医生管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody MedicalDoctor medicalDoctor)
    {
        return toAjax(medicalDoctorService.updateMedicalDoctor(medicalDoctor));
    }

    /**
     * 删除医生管理
     */
    @PreAuthorize("@ss.hasPermi('medical:doctor:remove')")
    @Log(title = "医生管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{doctorIds}")
    public AjaxResult remove(@PathVariable Long[] doctorIds)
    {
        return toAjax(medicalDoctorService.deleteMedicalDoctorByDoctorIds(doctorIds));
    }

    /**
     * 上传医生头像
     */
    @PreAuthorize("@ss.hasPermi('medical:doctor:edit')")
    @Log(title = "医生管理", businessType = BusinessType.UPDATE)
    @PostMapping("/uploadAvatar")
    public AjaxResult uploadAvatar(@RequestParam("file") MultipartFile file, @RequestParam("doctorId") Long doctorId)
    {
        try {
            // 添加详细的文件验证
            if (file == null || file.isEmpty()) {
                return error("上传文件不能为空");
            }
            // 检查文件大小
            if (file.getSize() == 0) {
                return error("文件大小为0");
            }
            // 检查文件名，如果为空则记录日志
            String originalFilename = file.getOriginalFilename();
            if (originalFilename == null || originalFilename.trim().isEmpty()) {
                // 记录警告日志但不阻止上传，因为MinIOUtils可能能处理
                logger.warn("上传的文件名为空，doctorId: {}", doctorId);
            }
            // 验证文件类型
            String contentType = file.getContentType();
            if (contentType == null || !contentType.startsWith("image/")) {
                return error("只能上传图片文件");
            }
            // 记录上传信息用于调试
            logger.info("上传医生头像 - doctorId: {}, 文件名: {}, 大小: {}, 类型: {}",
                    doctorId,
                    originalFilename != null ? originalFilename : "null",
                    file.getSize(),
                    contentType);
            String avatarUrl = medicalDoctorService.uploadAvatar(file, doctorId);
            return success(avatarUrl);
        } catch (Exception e) {
            logger.error("医生头像上传失败, doctorId: {}", doctorId, e);
            return error("医生头像上传失败: " + e.getMessage());
        }
    }

}